"use strict";

import './main.less';

import Xhr from '../utils/xhr';
import mainHtml from './main.tpl.html';
import main2Html from './main2.tpl.html';
import main3Html from './main3.tpl.html';
import main4Html from './main4.tpl.html';
import mainErrorHtml from './main.error.tpl.html';
import Tool from '../utils/tool';

import Modal from '../components/modal';
import {
    showActionSheet
} from '../components/action-sheet';
import AppsInfo from '../utils/apps-info';
import ListData from '../utils/mock-list-data';
import Loading from '../components/loading';
import Workplus from '../utils/workplus';
import Dialog from '../components/modal';
import Constant from '../utils/constant';

export default {
    // initialization page
    pageIndex: 1,
    pageSize: 20,
    loadingMore: false,
    loadingRefresh: false,
    hasMore: false,
    currentRes: null,
    init() {
        this.render();
    },
    render() {
        Loading.show();
        var self = this;
        // alert("main--------------->Promise");
        Promise.all([self.getUserInfo(), self.getAppInfo(), self.getTheme()])
            .then(function(res) {
                console.log('promise success');
                // alert("main--------------->Promise callback");
                self.initCtx(res);
            })
            .catch(function(err) {
                alert(err);
                 // alert("main--------------->Promise exception");
                self.initError("错误：初始化数据失败");
            });

    },
    getTheme() {
        return new Promise(function(resolve, reject) {
            if (window.cordova) {
                Workplus.getTheme(function(res) {
                    resolve(res);
                })
            } else {
                resolve();
            }
        })
    },
    getUserInfo() {
        return new Promise(function(resolve, reject) {
            // var orgId = "1df94799-fd32-49c3-b6d1-f7c9eb6caf49"
            // if(Constant.STATUS.ENV == "DEV"){
            //     orgId = "18590d66-26fe-4e78-9344-496370670ccf";
            // }
            if (window.cordova) {
                Workplus.getCurrentUserInfo(function(result) {
                    resolve({
                        orgId: result.employee.org_code,
                        domainId: result.employee.domain_id,
                        username: result.username
                    })
                }, function(err) {
                    reject("cordova err");
                });
            } else {
                // 测试环境org_id 18590d66-26fe-4e78-9344-496370670ccf
                // 正式环境org_id 1df94799-fd32-49c3-b6d1-f7c9eb6caf49
                resolve({
                    orgId: "1df94799-fd32-49c3-b6d1-f7c9eb6caf49",
                    // orgId: "18590d66-26fe-4e78-9344-496370670ccf",
                    domainId: "rfchina",
                    username: "maoguodao"
                })
            }
        })
    },
    getAppInfo() {
        var self = this;
        return new Promise(function(resolve, reject) {

            if (self._getQueryString("type")) {
                // find方法有问题？
                var filterArr = AppsInfo.filter(function(item) {
                    return item.type == self._getQueryString("type");
                });
                window.currentApp = filterArr[0];

                // window.history.replaceState(null, "", "/");

                resolve(window.currentApp);
            } else {
                if (window.currentApp) {
                    resolve(window.currentApp);
                } else {
                    reject("错误：未找到应用信息");
                }
            }
        })

    },
    hasLoadMoreFunction(appType){
        const hasLoadMoreFunctionApps = ["processesCenter","news","informations"];
        if(hasLoadMoreFunctionApps.indexOf(appType) !== -1){
            return true;
        }else{ 
            return false;
        }
    },
    initCtx(res) {
        // alert("main--------------->initCtx begin");
        this.currentRes = res;
        var currentUser = res[0];
        var currentApp = res[1];
        var currentTheme = res[2];
        var defaultTabIndex = 0;
        var titleColor = this.getTitleColor(currentTheme);
        
        if (currentApp.type !== "newcir5") {
            if (currentApp.type == "business") {
                // 配置
                var tpl = Tool.renderTpl(main3Html);
                // 渲染
                $('.home-page').html(tpl);
                // 获取可发起的申请
                this.initAppList(res);
            } else {
                if (currentApp.type == "processesCenter") {
                    // 配置
                    var tpl = Tool.renderTpl(main4Html, {
                        hasTabs: currentApp.tabs || false,
                        tabs: currentApp.tabs || {}
                    });
                } else {
                    // 配置
                    var tpl = Tool.renderTpl(mainHtml, {
                        hasTabs: currentApp.tabs || false,
                        tabs: currentApp.tabs || {}
                    });
                }
                // 渲染
                $('.home-page').html(tpl);

                // 获取缓存，判断选中的tab
                // alert("main--------------->initCtx setSessionStroage begin");
                var appType = sessionStorage.getItem('appType');
                if(appType && appType === window.currentApp.type){
                    var index = sessionStorage.getItem('index'); 
                    this.setActiveTab(index);
                }else{
                    // 输入值
                    if (currentApp.tabs) {
                        this.setActiveTab(defaultTabIndex);
                    };
                }             
                // alert("main--------------->initCtx setSessionStroage end");   
                this.initList(res);

                if (window.currentApp.type === "myApp") {
                    $('.pull-to-refresh-layer').hide();
                }
            }
        } else {
            Loading.hide();
            var tpl = Tool.renderTpl(main2Html);
            $('.home-page').html(tpl);
        }
        $('.navbar-custom').css("background", titleColor);
        $('.title-value').html(currentApp.name);
        this.bindEvent();

    },
    initLoadMorePlaceholder() {
        var $$ = Dom7;
        if (this.hasLoadMoreFunction(window.currentApp.type) && $$(".infinite-scroll-preloader").length == 0) {
            var placeholderHTML = '<div class="infinite-scroll-preloader">' +
                '<div class="preloader"></div>' +
                '</div>';
            $$('.page-content').addClass('infinite-scroll');
            $$('#content-wrap').append(placeholderHTML);
        }
    },
    initError(info) {
        var tpl = Tool.renderTpl(mainErrorHtml, {
            errorInfo: info
        });
        // 渲染
        $('.title-value').html("error");
        $('.home-page').html(tpl);
        this.getDone();
    },
    initList(res) {
        var self = this;
        var myApp = new Framework7();
        var $$ = Dom7;
       
        this.getListData(res, "refresh", this.pageIndex);
        
        // 流程中心搜索功能 2017/05/09 pangchaogao
        if (window.currentApp.type === "processesCenter") {
            var timeoutTag = "";
            $$('.searchbar-input input').on('keydown', function (e) {
                if (timeoutTag != ""){
                    clearTimeout(timeoutTag);
                    timeoutTag = "";
                }
                timeoutTag = setTimeout(function () {
                    var keyWords = $$('.searchbar-input input').val();
                    self.getListData(res, "refresh", 1, keyWords);
                }, 1000);
            });
            $$('.searchbar-clear').on('click', function(e) {
                var val = $$('.searchbar-input input').val();
                if (val != "") {
                    $$('.searchbar-input input').val("");
                    $$('.searchbar-input input').trigger('keydown');
                }
            });
        }

        // 下拉刷新
        $$('.pull-to-refresh-content').on('refresh', function(e) {
            if (self.loadingRefresh) return;
            if (window.currentApp.type === "myApp") {
                 $('.pull-to-refresh-layer').show();
            }
            self.loadingRefresh = true;
            if (window.currentApp.type === "processesCenter") {
                var keyWords = $$('.searchbar-input input').val();
                self.getListData(res, "refresh", 1, keyWords);
            } else {
                self.getListData(res, "refresh");
            }
            
        });
        // 上拉加载
        if (this.hasLoadMoreFunction(window.currentApp.type)) {
            $$('.infinite-scroll').on('infinite', function() {
                if (self.loadingMore) return;
                self.loadingMore = true;
                var lastIndex = $$('.list-block li').length;
                var currentIndex = Math.ceil(lastIndex / self.pageSize);
                var nextPageIndex = parseInt(currentIndex) + 1;
                if(self.hasMore){
                    if (window.currentApp.type === "processesCenter") {
                        var keyWords = $$('.searchbar-input input').val();
                        self.getListData(res, "append", nextPageIndex, keyWords);
                    } else {
                        self.getListData(res, "append", nextPageIndex);
                    }
                }else{
                     $$('.infinite-scroll-preloader').remove();
                }
            })
        }
    },
    // 初始化可发起的申请 2017/03/13 pang chaogao
    initAppList(res) {
        var self = this;
        var myApp = new Framework7();
        var $$ = Dom7;
        this.getAppListData(res);
    },
    hasMoreItem(res) {
        if (!this.hasLoadMoreFunction(window.currentApp.type)) {
            this.getMoreItemDone();
            return;
        };
        if (res.length == this.pageSize) {
            this.hasMore = true;
        } else if (res.length < this.pageSize) {
            this.hasMore = false;
            this.getMoreItemDone();
        } else {
            console.error("出错拉～");
            this.getMoreItemDone();
        }
        console.log("hasMore", this.hasMore);
    },
    getMoreItemDone() {
        var myApp = new Framework7();
        var $$ = Dom7;
        this.loadingMore = false;
        myApp.detachInfiniteScroll($$('.infinite-scroll'));
        $$('.infinite-scroll-preloader').remove();
    },
    getListData(res, type, pageIndex, keyWords) {
        var self = this;
        var currentUser = res[0];
        var currentApp = res[1];

        var tabType = currentApp.tabs ? currentApp.tabs[window.currentTabIndex].type : "";

        // this.renderListData(ListData, type);
        Xhr.getList({
            reqParams: {
                type: currentApp.type
            },
            data: {
                tabType: tabType,
                user: currentUser.username,
                orgId: currentUser.orgId,
                domainId: currentUser.domainId,
                pageIndex: pageIndex || 1,
                pageSize: self.pageSize,
                keyWords: keyWords || ""
            },
            success: function(res, status) {
                console.log(res);
                if (res.status == 0) {
                    self.hasMoreItem(res.result);
                    self.renderListData(res.result, type);
                } else {
                    self.initError("列表数据请求失败。")
                }
            },
            error: function(err) {
                self.initError("列表数据请求失败。")
            }
        })
    },
    getAppListData(res) {
        var self = this;
        var currentUser = res[0];
        var currentApp = res[1];

        var tabType = currentApp.tabs ? currentApp.tabs[window.currentTabIndex].type : "";

        // this.renderListData(ListData, type);
        Xhr.getAppList({
            reqParams: {
                type: currentApp.type
            },
            data: {
                tabType: tabType,
                user: currentUser.username,
                orgId: currentUser.orgId,
                domainId: currentUser.domainId
            },
            success: function(res, status) {
                console.log(res);
                if (res.status == 0) {
                    self.renderAppListData(res.result);
                } else {
                    self.initError("数据请求失败。")
                }
            },
            error: function(err) {
                self.initError("数据请求失败。")
            }
        })
    },
    renderListData(data, type) {
        var myApp = new Framework7();
        var $$ = Dom7;
        var self = this;
        if (type == "append") {
            this.isAppendItemToList(data);
        } else if (type == "refresh") {
            this.isRefreshList(data);
        }
    },
    renderList(data) {
        var $$ = Dom7;
        var ptrContent = $$('.pull-to-refresh-content');
        var base64 = "";
        // var data = ListData;

        data.forEach(function(item) {
            var hasImage = (item.image_url) ? '<div class="item-img-wrapper">' +
                '<img class="item-img" src=' + item.image_url + ' alt="">' +
                '</div>' : "";
            var formatTime = (item.publish_time.length > 10) ? item.publish_time.split(" ")[0] : item.publish_time;
            var itemHTML = '<li class="item" data-url=' + item.link_url + '>' + hasImage +
                '<div class="item-ctx">' +
                '<div class="item-title-info">' + item.title + '</div>' +
                '<div class="item-subtitle">' +
                '<div class="publish-time">' + formatTime + '</div>' +
                ' </div>' +
                '</div>' +
                '<div class="item-flag">' +
                ' <img src=' + base64 + ' alt="">' +
                '</div>' +
                '</li>';
            // 前插新列表元素
            ptrContent.find('ul').append(itemHTML);
        })

       

    },
    renderAppListData(data) {
        var $$ = Dom7;
        var ptrContent = $$('.main3-page');
        if (data.length > 0) {
            data.forEach(function(item) {
                var appHTML = '<li data-openurl=' + item.open_url + '><div class="item-link item-content">' + 
                '<div class="item-media"><img src="' + item.icon_url + '" alt=""></div>' + 
                '<div class="item-inner"><div class="item-title">' + item.name + '</div>' + 
                '<div class="item-after"></div></div>' +
                '</div></li>';
                ptrContent.find('.main4-list').append(appHTML);
            });
            Loading.hide();
        }
    },
    isAppendItemToList(data) {
        // 上拉加载
        this.loadingMore = false;
        if (data.length > 0) {
            this.initLoadMorePlaceholder(); //有数据时才添加placeholder
            this.renderList(data);
        }
    },
    isRefreshList(data) {
        // 下拉刷新
        var myApp = new Framework7();
        var $$ = Dom7;
        var self = this;
        var ptrContent = $$('.pull-to-refresh-content');
        if (window.currentApp.type === "myApp") {
            $('.pull-to-refresh-layer').hide();
        }
        ptrContent.find('ul').html("");
        if (data.length > 0) {
            this.renderList(data);
        } else {
            if ($('.pull-to-refresh-content').find('.no-data').length == 0) {
                var noDataHTML = '<div class="no-data">暂无数据，下拉刷新数据。</div>';
                $('.pull-to-refresh-content').append(noDataHTML);
            };
        }
        myApp.pullToRefreshDone();
        self.loadingRefresh = false;
        Loading.hide();
    },
    getDone() {
        var myApp = new Framework7();
        var $$ = Dom7;
        Loading.hide();
        self.loadingMore = false;
    },
    setActiveTab(index) {
        var self = this;
        $('.sub-tab').removeClass('sub-tab-active');
        $('.sub-tab').eq(index).addClass('sub-tab-active');
        window.currentTabIndex = index;
        self.loadingMore = false;
        self.hasMore = false;
    },
    // bind events
    bindEvent() {
        var $$ = Dom7;
        $('.sub-tab').on('click', this.clickTab.bind(this));
        $('.exit-btn').on('click', this.cliekExitBtn.bind(this));
        var _this = this;
        var bindings = [{
            element: '.list-block',
            event: 'click',
            selector: '.item',
            handler: function() {
                _this.clickItemEvent($$(this));
            }
        }, {
            element: '.main2-list', //我的传阅
            event: 'click',
            selector: 'li',
            handler: function() {
                _this.clickMain2ItemEvent($$(this));
            }
        }, {
            element: '.main3-list', //业务申请
            event: 'click',
            selector: 'li',
            handler: function() {
                _this.clickMain3ItemEvent($$(this));
            }
        },{
            element: '.main4-list', //业务申请
            event: 'click',
            selector: 'li',
            handler: function() {
                _this.clickMain4ItemEvent($$(this));
            }
        }];
        this.bindPostMessage();
        Tool.bindEvents(bindings);
    },
    bindPostMessage(){
        window.addEventListener('message',function(e){
            console.log(e);
        },false);
    },
    refreshCurrentPage(){
        var self = this;
        if (window.currentApp.type === "processesCenter") {
            $(".searchbar-input input").val("");
        }
        // 刷新当前页面
        Promise.all([self.getUserInfo(), self.getAppInfo()])
        .then(function(res) {
            self.getListData(res, "refresh", 1);
        })
        .catch(function(err) {
            self.initError("错误：初始化数据失败");
        });
    },
    cliekExitBtn() {
        if (this.currentApp.type === "processesCenter") {
            sessionStorage.setItem("appType", "processesCenter");
            sessionStorage.setItem("index", 0);
        }
        Workplus.getOut();
    },
    clickTab(e) {
        Loading.show();
        var self = this;
        var $$ = Dom7;
        var ptrContent = $$('.pull-to-refresh-content');
        ptrContent.find('ul li').remove();
        $$(".no-data").remove();

        if (window.currentApp.type === 'processesCenter') {
            sessionStorage.setItem('appType', window.currentApp.type);
            sessionStorage.setItem('index', $(e.currentTarget).index());
        }
        this.setActiveTab($(e.currentTarget).index());
        this.refreshCurrentPage();
    },
    clickMain2ItemEvent(currentTarget) {
        var targetType = currentTarget[0].attributes["data-id"].nodeValue;
        var filterArr = window.currentApp.list.filter(function(item) {
            return item.type == targetType
        });
        var targetItem = filterArr[0];
        if (Constant.STATUS.ENV == 'test') {
            this.openWebView(targetItem.testUrl, window.currentApp.name);
        } else {
            this.openWebView(targetItem.productionUrl, window.currentApp.name);
        }
    },
    clickMain3ItemEvent(currentTarget) {
        var self = this;
        if (currentTarget[0].attributes["data-openurl"]) {
            var openUrl = currentTarget[0].attributes["data-openurl"].nodeValue;
            if (window.cordova) {
                if(self.isIOSPlatform()){
                    try{
                        Loading.show();
                        window.location.href = openUrl;
                    }catch(e){
                        Workplus.openWebView({url: openUrl, title: window.currentApp.name}, function(res){});
                    }
                }else{
                    openUrl = openUrl + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                    try{
                        var newWin2 = window.open(openUrl);
                        // newWin2.focus();
                        var listenerWin2 = setInterval(function(newWin2){
                            return function(){
                                if(newWin2.closed){
                                    clearInterval(listenerWin2);
                                    self.refreshCurrentPage();
                                }
                            }
                        }(newWin2),1000);
                    }catch(e){
                        window.open(openUrl);
                    }
                }
            } else {
                openUrl = openUrl + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                window.open(openUrl);
            }
            
        }

    },
    // 业务申请列表点击事件 2017/03/13 pang chaogao
    clickMain4ItemEvent(currentTarget) {
        var self = this;
        // console.log(currentTarget[0].attributes["data-openurl"]);
        // 非我的申请流程，点击打开申请页面
        if (currentTarget[0].attributes["data-openurl"]) {
            var openUrl = currentTarget[0].attributes["data-openurl"].nodeValue;
            if (window.cordova) {
                Workplus.setRfchinaCookies({
                    domain: ".rfchina.com"
                }, function(res) {
                    if (res) {
                        if(self.isIOSPlatform()){
                            try{
                                Loading.show();
                                window.location.href = openUrl;
                            }catch(e){
                                Workplus.openWebView({url: openUrl, title: window.currentApp.name}, function(res){
                                });
                            }
                        }else{
                            openUrl = openUrl + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                            // window.open(url);
                            try{
                                var newWin2 = window.open(openUrl);
                                // newWin2.focus();
                                var listenerWin2 = setInterval(function(newWin2){
                                    return function(){
                                        if(newWin2.closed){
                                            clearInterval(listenerWin2);
                                            self.refreshCurrentPage();
                                        }
                                    }
                                }(newWin2),1000);
                            }catch(e){
                                window.open(openUrl);
                            }
                        }
                    } else {
                        Modal.alert({
                            text: '打开失败： SET COOKIE ERROR'
                        });
                    }
                });
               
            } else {
                openUrl = openUrl + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                window.open(openUrl);
            }
        }
    },
    clickItemEvent(currentTarget) {
        // 打开除”我的传阅“轻应用；
        var self = this;
        var url = currentTarget[0].attributes["data-url"].nodeValue;
        // console.log(currentTarget[0].attributes["data-url"].nodeValue);
        // var mainView = myApp.addView('.view-main');
        // mainView.router.loadPage('page/detail.html?id=12345')
        if (window.currentApp.type !== "processesCenter") { //除了流程中心都是openWebView
            this.openWebView(url, window.currentApp.name);
        } else {
            if (window.cordova) {
                Workplus.setRfchinaCookies({
                    domain: ".rfchina.com"
                }, function(res) {
                    if (res) {
                        if(self.isIOSPlatform()){
                            try{
                                Loading.show();
                                window.location.href = url;
                            }catch(e){
                                Workplus.openWebView({url: url, title: window.currentApp.name}, function(res){
                                });
                            }
                        }else{
                            url = url + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                            // window.open(url);
                            try{
                                var newWin2 = window.open(url);
                                // newWin2.focus();
                                var listenerWin2 = setInterval(function(newWin2){
                                    return function(){
                                        if(newWin2.closed){
                                            clearInterval(listenerWin2);
                                            self.refreshCurrentPage();
                                        }
                                    }
                                }(newWin2),1000);
                            }catch(e){
                                window.open(url);
                            }
                        }
                    } else {
                        Modal.alert({
                            text: '打开失败： SET COOKIE ERROR'
                        });
                    }
                });
               
            } else {
                url = url + "&language=" + (window.navigator.userLanguage || window.navigator.language);
                window.open(url);
            }
        }

    },
    isIOSPlatform(){
        var u = navigator.userAgent;
        // var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        
        return isiOS;
    },
    openWebView(url, title) {
        if (window.cordova) {
            Workplus.openAuthNormalWebview({
                url: url || "",
                title: title || "404"
            }, function(res) {})
        } else {
            window.open(url || "");
        }
    },
    getTitleColor(res) {
        if (res && res.base_color) {
            return res.base_color.c1;
        } else {
            return "#1A98FF";
        }
    },
    _getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
};